package com.general.template.manager;

import com.general.template.enums.ResultEnum;
import com.general.template.exception.GeneralException;
import com.general.template.utils.RedisKeyConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @Author: 杰哥
 * Date: 2020/12/19 9:49
 * @Description:
 **/
@Configuration
public class ShiroTokenManager extends DefaultWebSessionManager {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String token = httpServletRequest.getHeader(RedisKeyConstant.TOKEN_KEY);
        Object user = redisTemplate.opsForValue().get(RedisKeyConstant.TOKEN_KEY + ":" + token);
        // user为null说明token不合法
        if (user == null) {
            return null;
        }
        if (StringUtils.isNotBlank(token)){
//            不为空返回token
            return token;
        }
        return super.getSessionId(request, response);
    }
}
